const canvas = document.getElementById('webgl')
const gl = getWebGLContext(canvas)

//此例 添加对片元着色器的第一次尝试 改变颜色


let VertexShaderSource =
    'attribute vec4 a_Position;\n' +
    'void main(){ \n' +
    '   gl_Position = a_Position;\n' +
    '   gl_PointSize = 10.0;\n' +
    '}\n'
let FragmentShaderSource =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' +
    'void main(){\n' +
    '    gl_FragColor = u_FragColor;\n' +
    '}\n'

function main() {
    initShaders(gl, VertexShaderSource, FragmentShaderSource)

    //新内容: 设置顶点位置
    let n = initVertexBuffers(gl)
    if (n < 0) {
        console.log('Failed to set the position of the vertices');
        return
    }

    //设置背景色
    gl.clearColor(0.5, 0.5, 0.5, 1)
    //清一下
    gl.clear(gl.COLOR_BUFFER_BIT)

    gl.drawArrays(gl.POINTS, 0, n)
}

function initVertexBuffers(gl) {
    let vertices = new Float32Array([
        0.0, 0.5, 
        -0.5, -0.5,
        0.5, -0.5
    ])
    let n = 3

    //创建缓冲区对象------新玩意：对象
    let vertexBuffer = gl.createBuffer()
    if (!vertexBuffer) {
        console.log('Failed to create the buffer object');
        return -1
    }

    //将缓冲区对象绑定到目标
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)

    //向缓冲区对象写入数据
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

    let a_Position = gl.getAttribLocation(gl.program, 'a_Position')

    //将缓冲区对象分配给a_Position变量
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)

    //连接a_Position变量与分配给它的缓冲区对象
    gl.enableVertexAttribArray(a_Position)

    return n
}